<?php
// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author jxy [415782189@qq.com]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------

namespace app\order\admin;

use app\admin\admin\Base;
use app\common\model\Order as OrderModel;
use app\order\model\OrderGoods;
use app\order\model\OrderGoodsExpress;
use app\order\model\OrderInfo;
use app\order\model\OrderRefund as RefundModel;
use think\Db;
use app\goods\model\Category;
use think\facade\Log;

/**
 * 订单控制器
 * @package app\Order\admin
 */
class Order extends Base
{
    /**
     * 订单列表
     * @return mixed
     * @author jxy [415782189@qq.com]
     */
    public function index($order_status = "")
    {
       cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 查询
        $param=$input = input('param.');
        $param['export'] = null;
        $param['store_name'] = null;
        $param['nickname'] = null;
        unset($param['export']);
        $export = $input['export'] ?? 0;
        $nickname = $input['nickname'] ?? "";
        $order_sn = $input['order_sn'] ?? "";
        $order_type = $input['order_type'] ?? "";
        $where = [];
        if ($order_sn) {
            $where[] = ['order.order_sn', 'like' ,'%'.$order_sn.'%'];
        }
        if ($order_status !== 'all' && $order_status !== '') {
            if($order_status == 5){
                $where[] = ['order.order_sn', 'in' , function($query){
                    $query->name("order_refund")->where("status","in",[0,1,2])->field("order_sn");
                }];
            }else{
                $where[] = ['order.status', 'eq' , $order_status];
            }
        }
        if ($order_type) {
            $where[] = ['order.order_type', 'eq' , $order_type];
        }
        if ($nickname) {
            $where[] = ['user.user_nickname', 'like', '%'.$nickname.'%'];      
        }      
        $where[] =  ['order.order_type', 'in' , [3]];
         //导出订单数据
        if($export==1){
            $this->toExcel($where);
            die;
        }        
        // 排序
        $order = 'order.create_time desc';
        $data_list = OrderModel::view("order")
                ->view("order_goods_info",true,"order.order_sn = order_goods_info.order_sn")
                ->view("user","user_nickname,head_img,mobile","order.user_id = user.id")
                ->where($where)
                ->order($order)
                ->paginate(15, false, ['query' => request()->param()])
                ->each(function($item){                  
                    $item['status_name'] = OrderModel::$order_status[$item['status']];
                    $item['order_type_name'] = OrderModel::$orderTypes[$item['order_type']];
                    $item['pay_type_name']= OrderModel::$payTypes[$item['pay_type']] ?? $item['pay_type'];  
                    $item["order_goods_list"] = OrderGoods::where("order_sn",$item["order_sn"])->order("id asc")->select();
                    $item['refund_count'] = RefundModel::where("status","in",[0,1,2])->where("order_sn",$item["order_sn"])->count();  
                    return $item;
                });     
        $order_status_list = OrderModel::$order_status;
        $this->assign('store_id', 0);
        $this->assign('order_type', $order_type);
        $this->assign('order_status', $order_status);
        $this->assign('list', $data_list);
        $this->assign('order_status_list', $order_status_list);
        $this->assign('order_typeArr', OrderModel::order_typeArr());
        $this->assign('pages', $data_list->render());
        return $this->fetch();
    }
    
     private function toExcel($where){
        $xlsName  = "订单列表";
        $xlsCell  = array(            
            array('user_nickname','昵称'),
            array('user_id','用户ID'),
            array('create_time','下单时间'),
            array('goods_name','商品名称'),
            array('sku_name','规格名称'),
            //array('sku_sn','SKU货号'),
            array('num','数量'),

            array('order_sn','订单号'),
            array('transaction_id','付款流水号'),
            array('status_name','订单状态'),

            array('pay_time','付款时间'),
            array('pay_type','付款类型'),
            array('real_money','成本'),

            array('goods_money',"总成本"),
            array('express_money','运费'),
            array('refund_status','退款'),
            array('express_no','运单号'),
            array('express_company_id','快递公司id'),
            array('express_company','快递公司'),

            array('receiver_name','收件人'),
            array('receiver_mobile','收件人电话'),
            array('receiver_province','省'),
            array('receiver_city','市'),
            array('receiver_district','区'),
            array('receiver_address','街道'),
        );
        $xlsData = OrderModel::view("order","transaction_id,user_id,payable_money,pay_type,real_money,create_time,pay_time")
            ->view("order_goods_list",true,"order.order_sn = order_goods_list.order_sn")
            ->view("order_goods_info",
                    "receiver_name,province,city,district,receiver_address,receiver_mobile,express_price",
                    "order.order_sn = order_goods_info.order_sn"
             )
           ->view("order_goods_express","express_company_id,express_company","order.order_sn = order_goods_express.order_sn","left")
            ->view("user","user_nickname,head_img,mobile","order.user_id = user.id")
            ->where($where)
            //->where("order_goods_list.order_status","not in",[5,6])
            ->select();

        foreach ($xlsData as $vv) {
            $excelData[0]['list'][]=[                   

                'user_nickname'=>$vv['user_nickname'],
                'user_id'=>$vv['user_id'],
                'create_time'=> $vv['create_time'],
                'goods_name'=>$vv['goods_name'],
                'sku_name'=>$vv['sku_name'],
                //'sku_sn'=> Db::name('goods_sku')->where('sku_id', $vv['sku_id'])->value('sku_sn'),
                'num'=>$vv['num'],

                'order_sn'=>$vv['order_sn'].'-'.$vv['id'],
                'transaction_id'=>$vv['transaction_id'],
                'status_name'=> OrderModel::$order_status[$vv['order_status']] ?? $vv['order_status'],

                'pay_time'=>$vv['pay_time'] ? date("Y-m-d H:i:s",$vv['pay_time']) : "",
                'pay_type'=> OrderModel::$payTypes[$vv['pay_type']] ?? $vv['pay_type'] ,
                'real_money'=>$vv['shop_price'],

                'goods_money'=>$vv['goods_money'],
                'express_money'=>$vv['express_price'],
                'refund_status'=>$vv['refund_money'],
                "express_no"=> $vv["express_no"],
                "express_company_id"=> $vv["express_company_id"],
                "express_company"=> $vv["express_company"],


                'receiver_name'=>$vv['receiver_name'],
                'receiver_mobile'=>$vv['receiver_mobile'],
                'receiver_province' => $vv['province'],
                'receiver_city'=>$vv['city'],
                'receiver_district'=>$vv['district'],
                'receiver_address'=>$vv['receiver_address'],
            ];
            $excelData[0]['sender'] = '';
        }
        $excelData = array_values($excelData);
        action_log('order_export', 'order', 0, UID,  $xlsData->count() . "条");
        $this->exportExcel($xlsName,$xlsCell,$excelData);
    }
    /**
     * 批量导入发货
     * author: php迷途小书童
     * created: 2022/3/22 13:27
     */
    public function do_edit_import()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $orders = json_decode($post['dataInfo'], true);
            $result = $this->getExcelData($orders);
            foreach ($result as $value) {
                if (!$value['express_no']) {
                    continue;
                }
                $explode = explode('-',$value['order_sn']);
                if (!isset($explode[1])) {
                    continue;
                }
                $param = [
                    'express_no' => $value['express_no'],
                    'express_company_id' => $value['express_company_id'],
                    'order_sn' => $explode[0],
                    'og_id' => $explode[1],
                ];
                Db::startTrans();
                try {
                    OrderGoodsExpress::importExpressExcel($param);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    Log::info($e->getMessage());
                }

            }
            return json(['code' => 1, 'msg' => '导入成功']);
        }
        return $this->fetch();
    }
    /**
     * 使用php生成器
     * @param $orders
     * author: php迷途小书童
     * created: 2021/6/28 9:59
     */
    public function getExcelData($orders)
    {
        foreach ($orders as $item) {
            yield $item;
        }
    }

    /**
     * @param int $aid 订单id
     * @author 似水星辰 [ 2630481389@qq.com ]
     * @created 2019/10/28 11:14
     */
    public function detail($order_sn = null)
    {
        $info = OrderModel::where("order_sn",$order_sn)->where("order_type","in",[3])->find();
        if(!$info){
            $this->error("参数错误");
        }

        $info['order_status'] = \app\common\model\Order::$order_status[$info['status']];
        $info['pay_type_name']= OrderModel::$payTypes[$info['pay_type']] ?? $info['pay_type'];  
        $info["order_info"] = OrderInfo::where("order_sn",$order_sn)->find();
        $goods = OrderGoods::where("order_sn",$order_sn)->select();
        foreach($goods as $item){
            $item["comment"] =  Db::name('goods_comment')
                    ->where('order_sn', $item['order_sn'])
                    ->where('goods_id', $item['goods_id'])
                    ->where('sku_id', $item['sku_id'])
                    ->field("content")
                    ->find();
            $item["refund"] = RefundModel::where('order_sn', $item['order_sn'])
                    ->where('goods_id', $item['goods_id'])
                    ->where('sku_id', $item['sku_id'])
                    ->field("id,refund_money,status")
                    ->order("id desc")
                    ->find();  
            if($item["refund"]){
                $item["refund"]["status_txt"] = RefundModel::$status[$item["refund"]["status"]] ?? $item["refund"]["status"];
            }
        }
        $info["order_goods"] = $goods;
        $info['order_express'] = OrderGoodsExpress::where(['order_sn' => $info['order_sn']])
            ->order('shipping_time', 'desc')
            ->select();
        $info['receive_time'] = OrderGoodsExpress::where(['order_sn' => $info['order_sn']])
            ->where('receive_time', '>', 0)
            ->value('receive_time');
        $info['comment_time'] = Db::name('goods_comment')->where([['order_sn', '=', $info['order_sn']], ['user_id', '=', $info['user_id']]])->value('create_time');
        //$info['refund_list'] = RefundModel::where("order_sn",$order_sn)->select();
        
        $action_list =\app\order\model\OrderAction::where("order_sn",$order_sn)->order("action_id desc")->select();
        foreach($action_list as $item){
            $item['order_status'] = \app\common\model\Order::$order_status[$item['order_status']];
        }        
        $info['action_list'] = $action_list;
        $result = OrderGoods::getSettleMoney($info, $info['order_info']['express_price']);      
        $info["total_settle_money"] = $result['total_settle_money'];  
        $info["settle_money"] = $result['settle_money'];   
        $info['refund_count'] = RefundModel::where("status","in",[0,1,2])->where("order_sn",$info["order_sn"])->count();       
        $this->assign('order_info', $info);
        return $this->fetch();
    }  
    

    /**
     * 根据商品分类cid获取商品列表
     */
    public function ajaxClass()
    {
        $cate_id = input('param.cid');
        $map1[] = ['is_delete', '=', 0];
        if (isset($cate_id) && $cate_id != 0) {
            $cid = Category::getChildsId($cate_id);
            if (count($cid)) {
                $map1[] = ['cid', 'in', $cid];
            } else {
                $map1[] = ['cid', '=', $cate_id];
            }
        }
        $data_list = Db::name('goods')->where($map1)->select();
        foreach ($data_list as $key => $value) {
            if ($value['is_spec'] == 1) {
                $data_list[$key]['sku'] = Db::name('goods_sku')->where(['goods_id' => $value['id'], 'status' => 1])->select();
            }
        }
        return json(array('ret' => 2, 'data' => $data_list, 'msg' => lang('查询成功')));
    }

 
    /*
     * 删除订单
     * */
    public function order_del($order_sn)
    {
        $res = Db::name("order")->where(['order_sn' => $order_sn])->setField('is_delete', 1);
        if ($res) {
            $this->success(lang('删除成功'));
        } else {
            $this->error(lang('删除失败'));
        }
    }
    
    /**
     * 查询支付订单是否有效
     * @param $order_sn
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2020/2/19 18:05
     */
    public function query_order($order_sn)
    {
        $order = OrderModel::where('order_sn', $order_sn)->field('transaction_id, pay_type, order_sn')->find();
        if ($order['pay_type'] == 'wxpay' || $order['pay_type'] == 'minipay') {
            $query_order['transaction_id'] = $order['transaction_id'];
            $query_order['order_sn'] = $order['order_sn'];
            $result = addons_action('WeChat', 'MiniPay', 'queryOrder', $query_order);
            if ($result['return_code'] == 'SUCCESS' && $result['return_msg'] == 'OK') {
                $this->success($result['trade_state_desc']);
            }
        } else {
            $this->error(lang('暂未开放'));
        }
    }
    public function verify_status()
    {
        
    }   

   
    /*
     *
     * 新订单提醒
     *
     */
    public function new_order()
    {
        
    }

      /**
     * 订单改价
     * @author 晓风  
     */
    public function edit_money(){
        $sn = input("order_sn");
        $money = input("money");
        if(!$sn || !$money){
            $this->error("请填写内容");
        }
        if(!is_numeric($money)){
            $this->error("金额格式非法");
        }
        Db::startTrans();
        try{
            $remark = input("remark");
            OrderGoods::editPayableMoney($sn, $money,$remark);                     
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("修改成功"); 
    }
   
}
